/**
 * 
 */
package com.googlecode.pcapj;

import java.io.File;
import java.io.IOException;

import org.bridj.Pointer;

import com.googlecode.pcapj.bridj.Wpcap;

/**
 * 
 */
class DumpFileReaderImpl extends PacketCaptureImpl implements DumpFileReader{
	private File file;
	private String sourceName;
	
	public DumpFileReaderImpl(File file, CapturedFactory capturedFactory) {
		super(capturedFactory);
		this.file = file;
	}

	/* (non-Javadoc)
	 * @see com.googlecode.pcapj.PacketCaptureImpl#getDefaultSnapLength()
	 */
	@Override
	int getDefaultSnapLength() {
		return 66535;
	}
	/* (non-Javadoc)
	 * @see com.googlecode.pcapj.PacketCaptureImpl#getDefaultTimeout()
	 */
	@Override
	int getDefaultTimeout() {
		return 0;
	}
	/* (non-Javadoc)
	 * @see com.googlecode.pcapj.PacketCaptureImpl#getSourceName()
	 */
	@Override
	String getSourceName() throws IOException{
		if(sourceName == null){
			Pointer<Byte> source = Pointer.allocateBytes(Wpcap.PCAP_BUF_SIZE);
			try{
				Pointer<Byte> fileName = Pointer.pointerToCString(file.getPath());
				@SuppressWarnings("unchecked")
				Pointer<Byte> nullPointer = Pointer.NULL; 
				try{
				    /* Create the source string according to the new WinPcap syntax */
				    if (Wpcap.pcap_createsrcstr( 
				    		source,               // variable that will keep the source string
				            Wpcap.PCAP_SRC_FILE,  // we want to open a file
				            nullPointer,          // remote host
				            nullPointer,          // port on the remote host
				            fileName,             // name of the file we want to open
				            getErrorBuffer()      // error buffer
				            ) != 0)
				    {
				    	throw new IOException(getErrorBuffer().getCString());
				    }

				}finally{
					fileName.release();
				}
				sourceName = source.getCString();
				
			}finally{
				source.release();	
			}
		}
		return sourceName;
	}
}
